package edu.sctu.jarime.june.day20150618.HttpURLConnection.util;


import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;

/**
 * Created by user19 on 2015/6/18.
 */
public class GetAndPostDemo {

    //get方法
    public static void getURLConnection(String path) throws Exception{

        URL url = new URL(path);
        URLConnection connection = url.openConnection();
        connection.connect();
        InputStream inputStream = connection.getInputStream();
        int b;
        byte[] butffer = new byte[2014];
        while ((b = inputStream.read(butffer)) != -1) {
            System.out.println(new String(butffer, 0, b, "utf-8"));
        System.out.println(connection.getContentEncoding());
        System.out.println(connection.getContentLength());
        System.out.println(connection.getContentType());
    }

    }
    //post方法
    public  static void postURLConnection(String path,HashMap<String,String> paramMap)throws Exception{

        String lastpath= PathUtilDemo.getpath(paramMap);
        System.out.println(lastpath);
        //对象处理
        URL url = new URL(path);
        URLConnection urlConnection = url.openConnection();
        //配置
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setUseCaches(false);
        HttpURLConnection httpURLConnection = (HttpURLConnection)urlConnection;
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.connect();
        //数据传输
        byte[] buffer =new byte[2014];
        int read;
        OutputStream outputStream = httpURLConnection.getOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.write(lastpath.getBytes());
        objectOutputStream.flush();
        objectOutputStream.close();
        InputStream inputStream = httpURLConnection.getInputStream();
        while ((read=inputStream.read(buffer))!=-1){

            System.out.println(new String(buffer));
        }

    }
}
